package com.umsoft.smart.framework.helper;

import com.umsoft.smart.framework.annotation.Inject;
import com.umsoft.smart.framework.util.CollectionUtil;
import com.umsoft.smart.framework.util.ReflectionUtil;
import org.apache.commons.lang3.ArrayUtils;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * 依赖注入助手类
 */
public final class IOCHelper {
    static {
        Map<Class<?>,Object> BEAN_MAP = BeanHelper.getBeanMap();
        if(CollectionUtil.isNotEmpty(BEAN_MAP)){
            BEAN_MAP.forEach((beanClass,beanInstance)->{
                //获取所有的成员变量
                Field[] beanFields = beanClass.getDeclaredFields();
                if(ArrayUtils.isNotEmpty(beanFields)){
                    for(Field beanField : beanFields){
                        if(beanField.isAnnotationPresent(Inject.class)){
                            Class<?> beanFieldClass = beanField.getType();
                            Object beanFieldInstance = BEAN_MAP.get(beanFieldClass);
                            if(beanFieldInstance != null){
                                ReflectionUtil.setField(beanInstance,beanField,beanFieldInstance);
                            }
                        }
                    }
                }
            });
        }
    }
}
